import sys
import time
import mysql.connector
import threading
# from followth_crawl import pool,getconn
import mysql.connector
def get_disk_serial_simple():
    """获取第一个硬盘序列号（简化版）"""
    try:
        import wmi
        c = wmi.WMI()
        for disk in c.Win32_DiskDrive():
            if disk.SerialNumber:
                return disk.SerialNumber.strip()
        return None
    except Exception as e:
        print(f"Error getting disk serial: {e}")
        return None

 
def getnodescount(conn):
    cursor_c=conn.cursor()
    sql="SELECT count(*) FROM nodes  WHERE  TIMESTAMPDIFF(MINUTE, opdate, NOW()) <= 10 "
    print(sql)
    cursor_c.execute(sql)
    result = cursor_c.fetchone()
    return result[0]
def getnodeorder(conn,diskid):
    print('getnodeorder',diskid)
    cursor_c=conn.cursor()
    sql=f"SELECT nodeid,nodename FROM nodes WHERE  TIMESTAMPDIFF(MINUTE, opdate, NOW()) <= 10   order by nodeid"  
    print(sql)
    cursor_c.execute(sql)
    result = cursor_c.fetchall()
    for index,row in enumerate(result):
        if row[1]==diskid:
            return index
    return 0
def getkeywords_test (conn,diskid):
    count=getnodescount(conn)
    cursor_c=conn.cursor()
    order=getnodeorder(conn,diskid)
    sql=f"SELECT keywords   ,ebay,ali FROM sku_keywords   "  
    if count>1:
        sql=sql + f" where mod(id,{count})={order}"  
    print(count,'->',order,'->',sql)
    
    cursor_c.execute(sql)
    result = cursor_c.fetchall()
    print(len(result))
    return result
def heartnode   (conn,diskid):
    # 心跳信息上传
    cursor_c=conn.cursor()
    sql=f"SELECT * FROM nodes WHERE nodename = '{diskid}'"  
    print(sql)
    cursor_c.execute(sql)
    result = cursor_c.fetchall()
    if result:
        print(f"节点 {diskid} 已存在")
        sql=f"UPDATE nodes SET opdate=NOW() WHERE nodename='{diskid}'"
        print(sql   )
        cursor_c.execute(sql)
        conn.commit()
        sql=f"insert into nodes_history(nodeid,nodename,opdate)  select nodeid,nodename,now() from nodes where nodename='{diskid}'"
        print(sql)
        cursor_c.execute(sql)
        conn.commit()
    else:
        sql=f"INSERT INTO nodes (nodename,  opdate,firstopdate) values('{diskid}',NOW(),NOW())" 
        print(sql)
        cursor_c.execute(sql)
        conn.commit()


if __name__ == "__main__":
     
    diskid=get_disk_serial_simple()
    # print(diskid)
    # conn=getconn(pool)
    # heartnode(conn,diskid)
    # nodeorder=getnodeorder(conn,'testnode')
    # print('节点顺序',nodeorder)
    # count=getnodescount(conn)   
    # print('节点数量',count)

    # getkeywords_test(conn,diskid)
    # print('*' * 50)
    # print('*' * 50)
    # getkeywords_test(conn,'testnode')
     